// 模拟登录状态和用户角色
let currentUserRole = null;

// 模拟菜单数据，基于角色
const menusByRole = {
    admin: [
        { label: '首页', path: '/dashboard' },
        {
            label: '管理',
            children: [
                { label: '用户管理', path: '/admin/user' },
                { label: '权限设置', path: '/admin/permissions' }
            ]
        }
    ],
    user: [
        { label: '首页', path: '/dashboard' },
        { label: '个人中心', path: '/user/profile' }
    ]
};

// 页面加载时检查登录状态
window.onload = () => {
    const storedUserRole = localStorage.getItem('currentUserRole');
    if (storedUserRole) {
        currentUserRole = storedUserRole;
        loadMenu();
    } else {
        document.getElementById('menu').classList.add('hidden');
    }
};

// 模拟登录函数
function login() {
    // 这里可以替换为真实的登录逻辑，比如通过API验证用户名密码
    alert("模拟登录成功！");

    // 假设登录的角色是 admin
    currentUserRole = 'admin';
    localStorage.setItem('currentUserRole', currentUserRole);
    loadMenu();
}

// 加载菜单
function loadMenu() {
    const menuContainer = document.getElementById('menu');
    menuContainer.innerHTML = ''; // 清空之前的菜单

    if (!menusByRole[currentUserRole]) {
        console.error('未知的角色或未分配菜单');
        return;
    }

    const menuData = menusByRole[currentUserRole];
    renderMenu(menuData, menuContainer);
    menuContainer.classList.remove('hidden');
    document.getElementById('login-section').style.display = "none";
}

// 递归渲染菜单
function renderMenu(data, container) {
    const ul = document.createElement('ul');
    data.forEach(item => {
        const li = document.createElement('li');
        if (item.path) {
            const a = document.createElement('a');
            a.href = item.path;
            a.textContent = item.label;
            li.appendChild(a);
        } else {
            li.textContent = item.label;
        }

        if (item.children && item.children.length > 0) {
            renderMenu(item.children, li);
        }

        ul.appendChild(li);
    });
    container.appendChild(ul);
}